<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/20/24
 * Time: 3:22 PM
 */

namespace App\Http\Controllers;

class ResourceController extends Controller
{
    const SUCCESS_CODE = 200;
    const ERROR_CODE   = -1;

    const SUCCESS_MESSAGE = '成功';
    const ERROR_MESSAGE   = '失败';


    /**
     * 返回code
     *
     * @var int
     */
    protected $code = self::SUCCESS_CODE;

    /**
     * 返回消息
     *
     * @var string
     */
    protected $message = '';
    /**
     * 返回数据
     *
     * @var array
     */
    protected $data = [];


    /**
     * 返回错误
     *
     * @param $code
     * @param $message
     * @param $data
     * @return mixed
     */
    public function responseWithError($message = self::ERROR_MESSAGE, $code = self::ERROR_CODE, $data = [])
    {
        $this->code    = $code;
        $this->message = $message;
        $this->data    = $data;

        return $this->responseWithArray();
    }


    /**
     * 格式化正确返回数据
     *
     * @param string $data
     * @param string $message
     * @return mixed
     */
    public function responseWithSuccess($data = [], $message = self::SUCCESS_MESSAGE)
    {
        $this->code    = self::SUCCESS_CODE;
        $this->message = $message;
        $this->data    = $data;

        return $this->responseWithArray();
    }


    /**
     * @param array $array
     * @return \Illuminate\Http\JsonResponse
     */
    private function responseWithArray(array $array = [])
    {
        $array = array_merge(['code' => $this->code, 'message' => $this->message, 'data' => $this->data], $array);

        return response()->json($array);
    }
}
